package playnsimple.core.state;

import java.util.HashMap;

public class StateMachine {
    
    private HashMap<String, BaseState> programStates = 
            new HashMap<String, BaseState>();
    private BaseState currentState;
    private String previousStateLabel;
    private Boolean isRunning;

    public StateMachine() {
        previousStateLabel = null;
        currentState = new InitState("init");
        isRunning = true;
    }

    public Boolean isRunning() {
        return isRunning;
    }

    public void update() {
        currentState.update();
    }
    
    public void paint() {
        currentState.paint();
    }

    public void addState(BaseState state) {
        programStates.put(state.getLabel(), state);
        state.machine = this;
    }

    public BaseState getState(String stateLabel) {
        return programStates.get(stateLabel);
    }

    public void changeState(String newStateLabel) {
        previousStateLabel = currentState.getLabel();
        currentState.exit();
        currentState = getState(newStateLabel);
        currentState.enter();
    }

    public void revert() {
        changeState(previousStateLabel);
    }

    public void stop() {
        previousStateLabel = currentState.getLabel();
        currentState.exit();
        currentState = null;
        isRunning = false;
    }

    public Boolean isInState(String stateLabel) {
        return currentState.getLabel() == stateLabel;
    }
}
